<template>
  <div class="slide-menu f_col f_jc_sb">
    <ul class="slide-menu-ul">
      <li class="f_row f_r_cnt">
        <p class="el-p">
          <el-button type="text" @click="addShowDialog" icon="el-icon-plus" class="addBtn">新建模块</el-button>
        </p>
      </li>
      <li :class="{'current-li':  item.id === currentId}" v-for="(item,index) in modlelist" :key="index" @click="handleClickMenu(item.id)">
        <router-link to="/" class="f_row f_r_cnt f_jc_sb">
          <p class="el-p-txt">{{item.name}}</p>
          <el-dropdown trigger="click" @command="dropdownCallBack">
            <span class="el-dropdown-link">
              <i class="el-icon-setting" v-if="item.id === currentId"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="edit">编辑</el-dropdown-item>
              <el-dropdown-item command="del">删除</el-dropdown-item>
            </el-dropdown-menu>
          </el-dropdown>
        </router-link>
      </li>
    </ul>
    <div class="export" @click="exportData"><el-button class="export-btn" icon="el-icon-document">导出数据</el-button></div>
    <el-dialog :title="formTitle" :visible.sync="dialogFormVisible">
      <el-form :model="form" :rules="rules"  ref="ruleForm">
        <el-form-item label="名称" prop="name" :label-width="formLabelWidth">
          <el-input v-model="form.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="上传图片" class="margin-bottom-img"></el-form-item>
        <el-upload
          class="avatar-uploader"
          action="/api/spot/uploadAttachment"
          :show-file-list="false"
          :on-success="handleAvatarSuccess"
          :before-upload="beforeAvatarUpload">
          <img v-if="imageUrl" :src="imageUrl" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon"></i>
        </el-upload>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="resetForm('ruleForm')">取 消</el-button>
        <el-button type="primary" @click="submit('ruleForm')">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog
      title="温馨提示"
      :visible.sync="dialogVisible"
      width="30%">
      <span>确定要删除此模块吗？</span>
      <span slot="footer" class="dialog-footer">
    <el-button @click="dialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="deleItem(currentId)">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
import axios from 'axios'
import PubSub from 'pubsub-js'
export default {
  name: 'slide-menu',
  data () {
    return {
      isFirst: false,
      currentId: '',
      modlelist: [],
      imageUrl: '',
      dialogFormVisible: false,
      dialogVisible: false,
      form: {
        name: '',
        imgPath: ''
      },
      rules: {
        name: [
          { required: true, message: '请输入名称', trigger: 'blur' },
          { min: 1, max: 100, message: '长度在 3 到 5 个字符', trigger: 'blur' }
        ]
      },
      formTitle: '新增',
      formLabelWidth: ''
    }
  },
  mounted () {
    this.isFirst = true
    this.getList()
  },
  methods: {
    // 点击一级菜单
    handleClickMenu (id) {
      this.currentId = id
      PubSub.publish('SELECTED-MODULE-ID', id)
    },
    dropdownCallBack (command) {
      if (command === 'edit') {
        this.dialogFormVisible = true
        this.formTitle = '编辑'
        this.modlelist.find((item, index) => {
          if (item.id === this.currentId) {
            this.form.name = item.name
            this.imageUrl = '/api/attachment/' + item.avatarPath
          }
        })
      }
      if (command === 'del') {
        this.dialogVisible = true
      }
    },
    addShowDialog () {
      this.dialogFormVisible = true
      this.formTitle = '新增'
      this.form.name = ''
      this.imageUrl = ''
    },
    addItem (obj) {
      let url = '/api/module/save'
      axios.post(`${url}?name=${obj.name}&avatarPath=${obj.imgPath}`)
        .then(res => {
          this.dialogFormVisible = false
          this.isFirst = false
          this.getList()
        }, res => {
          console.log('error')
        })
    },
    editItem (obj) {
      let url = '/api/module/update/' + this.currentId
      axios.post(`${url}?name=${obj.name}&avatarPath=${obj.imgPath}`)
        .then(res => {
          this.dialogFormVisible = false
          this.isFirst = false
          this.getList()
        }, res => {
          console.log('error')
        })
    },
    deleItem (id) {
      let url = '/api/module/delete/'
      axios.post(`${url}/${id}`)
        .then(res => {
          this.dialogVisible = false
          this.isFirst = true
          this.getList()
        }, res => {
          console.log('error')
        })
    },
    getList () {
      let url = '/api/module/list'
      axios.get(`${url}`)
        .then(res => {
          console.log(res)
          if (res.data.code === 'S200') {
            this.modlelist = res.data.data
            if (this.modlelist.length && this.isFirst) {
              this.currentId = this.modlelist[0].id // 默认以及菜单选中第一个
              PubSub.publish('SELECTED-MODULE-ID', this.currentId)
            }
            console.log(this.modlelist)
          }
        }, res => {
          console.log('error')
        })
    },
    handleAvatarSuccess (res, file) {
      this.imageUrl = URL.createObjectURL(file.raw)
      this.form.imgPath = res.data
    },
    submit (formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          let obj = {name: this.form.name, imgPath: this.form.imgPath}
          if (this.formTitle === '编辑') {
            this.editItem(obj)
          } else {
            this.addItem(obj)
          }
          this.resetForm(formName)
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    resetForm (formName) {
      this.dialogFormVisible = false
      this.$refs[formName].resetFields()
      this.imageUrl = ''
    },
    beforeAvatarUpload (file) {
      let allowTypeFlag = false
      if (file.type === 'image/jpeg' || file.type === 'image/png') {
        allowTypeFlag = true
      }
      const isLt2M = file.size / 1024 / 1024 < 10
      if (!allowTypeFlag) {
        this.$message.error('上传头像图片只能是 JPG 或 PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 10MB!')
      }
      return isLt2M && allowTypeFlag
    },
    exportData () {
      let loading = this.$loading({
        lock: true,
        text: '努力处理中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })

      let url = '/api/module/export'
      axios
        .get(`${url}`, {responseType: 'blob'})
        .then(function (response) {
          loading.close()
          let headerFileName = response.headers['content-disposition']
          let filename = headerFileName.split('=')[1]
          console.log(headerFileName)
          let blob = new Blob([response.data])
          let downloadElement = document.createElement('a')
          let href = window.URL.createObjectURL(blob) // 创建下载的链接
          downloadElement.href = href
          downloadElement.download = filename // 下载后文件名
          document.body.appendChild(downloadElement)
          downloadElement.click() // 点击下载
          document.body.removeChild(downloadElement) // 下载完成移除元素
          window.URL.revokeObjectURL(href) // 释放掉blob对象
        })
        .catch(function (error) {
          console.log(error)
          loading.close()
          this.$message.error('下载失败，请重试或联系技术人员')
        })
    }
  }
}
</script>

<style lang="stylus" rel="stylesheet/stylus">
  .slide-menu
    width 260px
    height 100%
    background #0F3A56
    .export
      padding 10px
      .export-btn
        width 100%
        background #0f3a56
        border none
        color #fff
    .slide-menu-ul
      padding 0
      li
        color #fff;
        padding 10px 30px
      .current-li
        position relative
        background rgba(0, 0, 0, .2)
        a,.el-icon-setting
          color #fff
      .current-li:before
        position absolute
        content ""
        top 0
        bottom 0
        left 0
        width 4px
        background #409EFF

      .el-icon-plus
        color #fff
        font-size 14px

      .el-p
        margin-left 6px
        width 100%
        .addBtn
          color #fff
          width 100%
          text-align left
      .el-p-txt
        margin-left 20px
        font-size 14px
        width 100%

    .margin-bottom-img
      margin-bottom 0

    .avatar-uploader .el-upload
      border: 1px dashed #d9d9d9
      border-radius: 6px
      cursor: pointer
      position: relative
      overflow: hidden

    .avatar-uploader .el-upload:hover
      border-color: #409EFF

    .avatar-uploader-icon
      font-size: 28px
      color: #8c939d
      width: 178px
      height: 178px
      line-height: 178px
      text-align: center

    .avatar
      width: 178px
      height: 178px
      display: block
</style>
